<?php

namespace Common\Model;
use Think\Model;

class UserModel extends Model{

    protected $_auto = array(
        array('create_time', NOW_TIME, self::MODEL_INSERT),
        array('reg_time', NOW_TIME, self::MODEL_INSERT),
        array('reg_ip', 'get_client_ip', self::MODEL_INSERT, 'function'),
        array('update_time', NOW_TIME, self::MODEL_BOTH),
        array('status', '1', self::MODEL_INSERT),

    );
    /**
     * 新增或更新
     * 
     * @return boolean fasle 失败 ， int 成功 返回完整的数据
     */
    public function update($data)
    {
        $data = $this->create($data);
        if (empty($data)) {
            return false;
        }
        
        if (empty($data['user_id'])) {
            $id = $this->add();
            if (! $id) {
                $this->error = '新增管理员出错';
                return false;
            }
        } else {
            $result = $this->where(array( 'user_id' => $data['user_id'] ))->save($data);
            if (false === $result) {
                $this->error = '更新管理员出错';
                return false;
            }
        }
        
        return $data;
    }

    /**
     * 管理员的权限规则
     *
     * @param integer $userID 用户ID
     */
    public function getUserRule($userID)
    {
        if (empty($userID)) {
            return false;
        }
        $result = $this->table('__USER__ a')
            ->join('__USER_GROUP__ g ON a.group_id = g.group_id')
            ->where('a.user_id = ' . $userID)
            ->find();
        return empty($result['rules']) ? false : explode(',', $result['rules']);
    }
	
}
